package com.xiao.framework.ds.autoconfigure.strategy;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;

/**
 * @author <a href="mailto:xiaoquanidea@163.com">hutiquan</a>
 * @since 2019-08-24 17:59
 */
public class LoadBalanceDataSourceStrategy implements MultiDataSourceDetermineStrategy {
  private AtomicInteger counter = new AtomicInteger(0);

  @Override
  public DataSource determineDataSource(List<DataSource> dataSources) {
    return Optional.ofNullable(dataSources).map(dataSourceList -> {
      int index = Math.abs(counter.getAndIncrement()) % dataSourceList.size();
      return dataSourceList.get(index);
    }).orElseGet(()->null);
  }
}
